package org.dcarew.model.core.impl;

import java.lang.reflect.Method;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.dcarew.model.ModelPlugin;
import org.dcarew.model.annotations.ClassName;
import org.dcarew.model.annotations.Icon;
import org.dcarew.model.annotations.Property;
import org.dcarew.model.core.IModelClass;
import org.dcarew.model.core.IModelProperty;
import org.dcarew.model.utils.CoreUtils;
import org.eclipse.swt.graphics.Image;

/**
 * 
 * 
 * @author Devon Carew
 */
public class ModelClass
	implements IModelClass
{
	private Class<?> 			clazz;
	
	private String				name;
	private Image				icon;
	
	private IModelProperty[]	properties;
	
	
	public ModelClass(Class<?> clazz)
	{
		this.clazz = clazz;
		
		init();
	}
	
	public Class<?> getClazz()
	{
		return clazz;
	}
	
	public String getName()
	{
		return name;
	}
	
	public Image getIcon()
	{
		return icon;
	}
	
	public IModelProperty[] getProperties()
	{
		return properties;
	}
	
	// implementation
	
	private void init()
	{
		// name property
		ClassName nameAnnotation = clazz.getAnnotation(ClassName.class);
		
		if (nameAnnotation != null)
			name = nameAnnotation.value();
		else
			name = CoreUtils.getShortName(clazz);
		
		// icon property
		Icon iconAnnotation = clazz.getAnnotation(Icon.class);
		
		if (iconAnnotation != null)
		{
			URL iconURL = clazz.getClassLoader().getResource(iconAnnotation.value());
			
			icon = ModelPlugin.getPlugin().getImage(iconURL);
		}
		else
		{
			icon = ModelPlugin.getImage("resources/icons/obj16/unknown_obj.gif");
		}
		
		// properties
		List<IModelProperty> list = new ArrayList<IModelProperty>();
		
		for (Method method : clazz.getMethods())
		{
			if (!method.isAnnotationPresent(Property.class))
				continue;
			
			Property propertyAnnotation = method.getAnnotation(Property.class);
			
			list.add(new ModelProperty(propertyAnnotation.name()));
		}
		
		properties = list.toArray(new IModelProperty[0]);
	}
	
}
